<?php

namespace App\Http\Middleware;

use App\Http\Utils\HelperUtils;
use Closure;

class AdminLoginMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next){
        $help = new HelperUtils();
        //判断是否登录
        if(!$request->session()->has('user')){
            $help->logout();
            return redirect('admin/login');
        }
        //获取当前时间
        $now = time();
        $lastTime = $request->session()->get('time');
        if(empty($lastTime)||($now-$lastTime>env('APP_ADMIN_LOGIN_TIMEOUT'))){
            //如果登录后无操作超过300秒
            $help->logout();
            return redirect('admin/login');
        }

        $request->session()->put('time', time());
        //下面做权限操作
        //这里获取session
        $nodes = session()->get('node');
        if(empty($nodes)){
            //表示没有权限
            $help->logout();
            return redirect(url('admin/login'));
        }else{
            $model = $help->getModelName();
            $controller = $help->getOneControllerName();
            $method = $help->getCurrentMethodName();

            foreach ($nodes as $key => $value) {
                $value = $help->object_to_array($value);
                // var_dump( ucwords($value['control_name']));
                if(ucwords($model) == ucwords($value['module_name']) &&ucwords($controller) == ucwords($value['control_name']) &&ucwords($method) == ucwords($value['action_name'])){
                    return $next($request);
                }
            }
            // echo $model.'--'.$controller.'--'.$method.'<br>';
        }
        //否则返回到首页，最好提示没权限
        // $help->logout();
        // return redirect('admin/login');
        abort('404','没有权限访问');
    }
}
